<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */
class appreportController extends appRain_Base_Core
{
    public $name = 'Appreport';


    public function indexAction()
    {
		
    }

	public function exportAction($type="jobs")
	{
		switch($type)
		{
			case 'jobs':
							$jobsrc = App::Session()->Read('jobsrc');
							$this->exportJobs($jobsrc);
							break;
							
			case 'payments':
							$jobsrc = App::Session()->Read('jobsrc');
							$this->exportPayments($jobsrc);
							break;
			
						 
		}
	}

	private function exportPayments($options = Array())
	{
	   
		$jobsrc = App::Session()->Read('paysrc');

		$cnd = "1 ";
		$cnd2 = " ";

		if(isset($jobsrc['startdate']) && $jobsrc['startdate']!="Start Date" && $jobsrc['startdate']!="" &&
			isset($jobsrc['enddate']) && $jobsrc['enddate']!='End Date' && $jobsrc['enddate']!='')
		{
			$cnd2 = " {$jobsrc['startdate']} to {$jobsrc['enddate']}";

			$starttime = strtotime("{$jobsrc['startdate']}");
			$endtime = strtotime("{$jobsrc['enddate']} 12pm") + (12*60*60);
			$cnd .= " AND (order_date >= {$starttime} AND order_date <= {$endtime}) ";
		}

		if(isset($jobsrc['str']) && $jobsrc['str']!="" && $jobsrc['str'] !='type')
		{
			$cnd .= " AND processor = '{$jobsrc['str']}' ";
			$cnd2 .= ", processor : {$jobsrc['str']} ";
		}

		if(isset($jobsrc['member']) && $jobsrc['member']!="")
		{
			$cnd .=" AND client_id = {$jobsrc['member']} ";
			$cnd2 .= ", client_id : {$jobsrc['member']} ";
		}

		$Payments = App::Model('Payment')->findAll("$cnd");

		$_data = Array();
		$t = 0;
		$tb = 0;
		$tPaid = 0;
		foreach($Payments['data'] as $Payment)
		{
			$Member = App::MemberManager()->Members($Payment['client_id']);
			$deposit = App::Component('Photocliping')->Helper('Data')->getDeposit($Payment['client_id']);
			$t +=  $Payment['total'];
			$tb +=  $deposit;
			$_data[] = Array(substr("{$Member['name']}",0,20),$Payment['processor'],App::Helper('Date')->dateFormated($Payment['order_date']),'$' . $Payment['total'],"\${$deposit}");
		}

		$_data[] = Array("","","","\${$t}","\${$tb}");



		$pdf = App::Plugin('pdf_Generator')
			   ->setPreHeader(array(
					'Report Create Date: ' . App::Helper('Date')->dateFormated(null,'long'),
					'Condition:' . $cnd2,
					'',
					'Total Payment On Job: $' . $t, 'Total Balance : $' . $tb ,
					'',
					'Chaked By__________________________, Created By : ' . App::Module('AdminpanelUI')->adminName()
				))
			   ->setRowOpts(array(
					array("width"=>"75"),
					array("width"=>"25"),
					array("width"=>"35"),
					array("width"=>"35"),
					array("width"=>"25"),
					array("width"=>"25"),
					array("width"=>"32"),
					array("width"=>"12"),
					array("width"=>"16"),
					array("width"=>"16")
			   ))
			   ->setReportTitle("Payments Report")
			   ->setHeader(array('Client Name','Processor', 'Payment Date',	'Amount','Balance'))
			   ->setData($_data)
			   ->setDownload(true)
			   ->Render();
		
		exit;
	}

	private function exportJobs($options = Array())
	{
	   
		$jobsrc = App::Session()->Read('jobsrc');
	   
		$cnd = "1 ";
		$cnd2 = ""; 
		if(isset($jobsrc['str']) && $jobsrc['str']!="")$cnd .= " AND title LIKE '%{$jobsrc['str']}%' ";

		if(isset($jobsrc['startdate']) && $jobsrc['startdate']!="Start Date" && $jobsrc['startdate']!="" &&
			isset($jobsrc['enddate']) && $jobsrc['enddate']!='End Date' && $jobsrc['enddate']!='')
		{
			$cnd2 = " {$jobsrc['startdate']} to {$jobsrc['enddate']}";

			$starttime = strtotime("{$jobsrc['startdate']} 12am");
			$endtime = strtotime("{$jobsrc['enddate']} 12pm") + (12*60*60);
			$cnd .= " AND (created >= {$starttime} AND created <= {$endtime}) ";
		}

		if(isset($jobsrc['member']) && $jobsrc['member']!="")
		{
			$cnd2 .= ", client_id : {$jobsrc['member']} ";
			$cnd .=" AND client_id = {$jobsrc['member']} ";
		}
		$Jobs = App::Model('Job')->findAll("{$cnd} ORDER by id ASC");

		$_data = Array();
		$t = 0;
		$ti = 0;
		$tPaid = 0;
		foreach($Jobs['data'] as $Job)
		{
			$EndDateData = App::Component('Photocliping')->helper('Data')->calculateEndDate($Job);
			$member = App::MemberManager()->Members($Job['client_id']);
			$color = '#FFFFFF';
			$sp = '-';
			$enddate = "-";
			if(!empty($EndDateData))
			{
				$enddate = $EndDateData['enddate'];
				$color = $EndDateData['legend'][0];
				$sp = "{$EndDateData['legend'][1]}";
			}

			$t += $Job['total'];
			$ti += $Job['num_images'];
			if($Job['paymentstatus']=='Paid') $tPaid += $Job['total'];
			$_data[] = Array
			(
				//$Job['id'],
				substr($Job['title'],0,10),
				(isset($member['name'])?substr($member['name'],0,10):""),
				//(isset($member['email'])?$member['email']:""),
				$Job['num_images'],
				'$' . $Job['total'],
				 App::Load("Helper/Date")->dateFormated($Job['created']),
				$enddate,
				App::Component('Photocliping')->Helper("Data")->displayStatus($Job['status']),
				$sp,
				substr(App::CategorySet()->idToName($Job['delivery_time']),0,8),
				App::Component('Photocliping')->Helper("Data")->paymentStatus($Job['paymentstatus'])
			);
		}
		$_data[] = Array("","","{$ti}","\${$t}","","","","","","");



		$pdf = App::Plugin('pdf_Generator')
			   ->setPreHeader(array(
					'Report Create Date: ' . App::Helper('Date')->dateFormated(null,'long'),
					'Condition:' . $cnd2,
					'',
					'Total Settlement: $' . $t, 'Total Paid: $' . $tPaid , 'Total Due : $' . ($t - $tPaid),
					'',
					'Chaked By__________________________, Created By : ' . App::Module('AdminpanelUI')->adminName()
				))
			   ->setRowOpts(array(
					array("width"=>"25"),
					array("width"=>"25"),
					array("width"=>"10"),
					array("width"=>"10"),
					array("width"=>"25"),
					array("width"=>"25"),
					array("width"=>"32"),
					array("width"=>"15"),
					array("width"=>"16"),
					array("width"=>"15")
			   ))
			   ->setHeader(array("Title","Name", "Imgs", "$$$", "Created", "ED", "Status", "%", "DT", "Payment"))
			   ->setReportTitle("Job Report")
			   ->setDownload(true)
			   ->setFooter()
			   ->setData($_data)
			   ->Render();
		
		exit;
	}
}
